package org.budo.swing.util;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import org.budo.support.lang.util.ThreadUtil;

/**
 * @author limingwei
 */
public class JDialogUtil {
    public static int showConfirmDialog(String message) {
        final List<Integer> option = new ArrayList<Integer>();

        final JDialog dialog = new JDialog();

        dialog.setSize(500, 150);
        dialog.setLocation(200, 200);

        dialog.setLayout(null);

        JLabel label = new JLabel(message);
        label.setBounds(20, 20, 500, 20);
        dialog.add(label);

        JButton button = new JButton("确认");
        button.setBounds(400, 60, 60, 30);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                option.add(JOptionPane.YES_OPTION);
                dialog.dispose(); // 销毁 dialog
            }
        });

        dialog.add(button);

        dialog.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) { /* 点击 X 不关闭 */ }
        });

        dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dialog.setAlwaysOnTop(true);
        dialog.setVisible(true);
        dialog.setModal(true);

        // 阻塞等待
        while (option.isEmpty()) {
            ThreadUtil.sleep(100);
        }

        // 确认后返回
        return option.get(0);
    }
}